package com.softcloud.comingforyuan.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.softcloud.comingforyuan.R;
import com.softcloud.comingforyuan.db.ExerciseDB;
import com.softcloud.comingforyuan.db.ExerciseOpenHelper;
import com.softcloud.comingforyuan.model.ActivityCollector;
import com.softcloud.comingforyuan.model.BaseActivity;
import com.softcloud.comingforyuan.model.Exercise;

import java.util.Calendar;
import java.util.List;

public class ExerciseActivity extends BaseActivity {

    private int lastHour;
    private int lastMin;
    private int lastSec;

    private TextView titleText;

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    private List<Exercise> exerciseList;
    private int exerciseNum;
    private int currId;
    private boolean isMistakeExercise;
    private ExerciseDB exerciseDB;
    private SQLiteDatabase db;

    private TextView questionTextView;
    private TextView analysesTextView;
    private RadioGroup questionRadioGroup;
    private RadioButton optionA;
    private RadioButton optionB;
    private RadioButton optionC;
    private RadioButton optionD;
    private Button analysesButton;
    private Button preButton;
    private Button nextButton;

    ExerciseOpenHelper helper;

    private boolean[] hasAnswered;
    private int[] myAnswers;
    private int[] radioButtonId;
    private boolean analysesVisible;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise);

        //设置标题文字
        titleText = (TextView)findViewById(R.id.title_text);
        titleText.setText("练习中");

        //建立初始化pref、helper、db
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        helper = new ExerciseOpenHelper(this,"exercise.db",null,1);
        db = helper.getWritableDatabase();
        exerciseDB = ExerciseDB.getInstance(this);

        //判断是全部练习还是错题联系并加载习题
        isMistakeExercise = pref.getBoolean("practiseMistake",false);
        if(!isMistakeExercise){
            exerciseList = exerciseDB.loadAllExercise();
        }else {
            exerciseList = exerciseDB.loadWrongExercise();
        }

        //初始化习题参数
        exerciseNum = exerciseList.size();
        hasAnswered = new boolean[exerciseNum];
        myAnswers = new int[exerciseNum];
        analysesVisible = false;

        //实例化控件
        questionTextView = (TextView)findViewById(R.id.exercise_question);
        analysesTextView = (TextView)findViewById(R.id.exercise_text_analyses);
        questionRadioGroup = (RadioGroup)findViewById(R.id.exercise_radio_group);
        optionA = (RadioButton)findViewById(R.id.exercise_optionA);
        optionB = (RadioButton)findViewById(R.id.exercise_optionB);
        optionC = (RadioButton)findViewById(R.id.exercise_optionC);
        optionD = (RadioButton)findViewById(R.id.exercise_optionD);
        analysesButton = (Button)findViewById(R.id.exercise_button_analyses);
        preButton = (Button)findViewById(R.id.exercise_button_pre);
        nextButton = (Button)findViewById(R.id.exercise_button_next);

        radioButtonId = new int[4];
        radioButtonId[0] = R.id.exercise_optionA;
        radioButtonId[1] = R.id.exercise_optionB;
        radioButtonId[2] = R.id.exercise_optionC;
        radioButtonId[3] = R.id.exercise_optionD;

        //Button设置监听器
        analysesButton.setOnClickListener(new AnalysesButtonListener());
        preButton.setOnClickListener(new PreButtonListener());
        nextButton.setOnClickListener(new NextButtonListener());

        //初始化习题id并加载相应的页面
        currId = 0;
        updatePage(exerciseList.get(currId));
    }

    private void updatePage(Exercise currExercise){
        questionTextView.setText(currExercise.getQuestion());
        analysesTextView.setText(currExercise.getAnalyses());
        optionA.setText(currExercise.getOptionA());
        optionB.setText(currExercise.getOptionB());
        optionC.setText(currExercise.getOptionC());
        optionD.setText(currExercise.getOptionD());
        preButton.setText("上一题");
        nextButton.setText("下一题");
        if(currId == 0){
            preButton.setText("返回首页");
        }
        if(currId == exerciseNum-1){
            nextButton.setText("提交答案");
        }
        if(hasAnswered[currId]){
            int selected = myAnswers[currId];
            questionRadioGroup.check(radioButtonId[selected-1]);
        }else{
            questionRadioGroup.clearCheck();
        }
        analysesVisible = false;
        analysesTextView.setVisibility(View.INVISIBLE);
    }

    class PreButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            if(currId == 0){
                Intent intent = new Intent(ExerciseActivity.this,MainActivity.class);
                startActivity(intent);
            }else {
                int selected = 0;
                switch (questionRadioGroup.getCheckedRadioButtonId()){
                    case R.id.exercise_optionA:
                        selected = 1;
                        break;
                    case R.id.exercise_optionB:
                        selected = 2;
                        break;
                    case R.id.exercise_optionC:
                        selected = 3;
                        break;
                    case R.id.exercise_optionD:
                        selected = 4;
                        break;
                    case -1:
                        selected = -1;
                        break;
                }
                if(selected != -1){
                    myAnswers[currId] = selected;
                    hasAnswered[currId] = true;
                }
                currId--;
                updatePage(exerciseList.get(currId));
            }
        }
    }
    class NextButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            if(currId == exerciseNum-1){
                int selected = 0;
                switch (questionRadioGroup.getCheckedRadioButtonId()){
                    case R.id.exercise_optionA:
                        selected = 1;
                        break;
                    case R.id.exercise_optionB:
                        selected = 2;
                        break;
                    case R.id.exercise_optionC:
                        selected = 3;
                        break;
                    case R.id.exercise_optionD:
                        selected = 4;
                        break;
                    case -1:
                        selected = -1;
                        break;
                }
                if(selected != -1){
                    myAnswers[currId] = selected;
                    hasAnswered[currId] = true;
                }

                boolean answeredAll = true;
                for(int i=0;i<exerciseNum;i++){
                    answeredAll = answeredAll && hasAnswered[i];
                }
                if(answeredAll){
                    for(int i=0;i<exerciseNum;i++){
                        exerciseDB.setCurrAnswer(exerciseList.get(i).getId(),myAnswers[i]);
                    }
                    List<Exercise> wrongList = exerciseDB.loadWrongExercise();
                    if(wrongList.size() != 0){
                        editor = pref.edit();
                        editor.putBoolean("hasMistake",true);
                        editor.commit();
                    }else {
                        editor = pref.edit();
                        editor.putBoolean("hasMistake",false);
                        editor.commit();
                    }
                    Intent intent = new Intent(ExerciseActivity.this,MistakeActivity.class);
                    startActivity(intent);
                }else{
                    Toast.makeText(ExerciseActivity.this,"请答完所有题目后再提交",Toast.LENGTH_SHORT).show();
                }
            }else {
                int selected = 0;
                switch (questionRadioGroup.getCheckedRadioButtonId()){
                    case R.id.exercise_optionA:
                        selected = 1;
                        break;
                    case R.id.exercise_optionB:
                        selected = 2;
                        break;
                    case R.id.exercise_optionC:
                        selected = 3;
                        break;
                    case R.id.exercise_optionD:
                        selected = 4;
                        break;
                    case -1:
                        selected = -1;
                        break;
                }
                if(selected != -1){
                    myAnswers[currId] = selected;
                    hasAnswered[currId] = true;
                }
                currId++;
                updatePage(exerciseList.get(currId));
            }
        }
    }
    class AnalysesButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            if(!analysesVisible){
                analysesTextView.setVisibility(View.VISIBLE);
                analysesVisible = true;
            } else {
                analysesTextView.setVisibility(View.INVISIBLE);
                analysesVisible = false;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //判断是全部练习还是错题联系并加载习题
        isMistakeExercise = pref.getBoolean("practiseMistake",false);
        if(!isMistakeExercise){
            exerciseList = exerciseDB.loadAllExercise();
        }else {
            exerciseList = exerciseDB.loadWrongExercise();
        }

        //初始化习题参数
        exerciseNum = exerciseList.size();
        hasAnswered = new boolean[exerciseNum];
        myAnswers = new int[exerciseNum];
        analysesVisible = false;

        currId = 0;
        updatePage(exerciseList.get(currId));
    }


    @Override
    public void onBackPressed() {
        Calendar calendar = Calendar.getInstance();
        int currHour = calendar.get(Calendar.HOUR);
        int currMin = calendar.get(Calendar.MINUTE);
        int currSec = calendar.get(Calendar.SECOND);
        if(currHour == lastHour && currMin == lastMin && currSec-lastSec<=2){
            ActivityCollector.finishAll();
        }else{
            lastHour = currHour;
            lastMin = currMin;
            lastSec = currSec;
            Toast.makeText(this, "再次点击退出程序", Toast.LENGTH_SHORT).show();
        }
    }
}
